Raspberry Pi 3 Cookbook for Python Programmers by Tim Cox

Raspberry Pi 3 Cookbook for Python Programmers by Tim Cox

Author:Tim Cox [Tim Cox]
Language: eng
Format: epub, mobi
Tags: COM067000 - COMPUTERS / Hardware / General, COM038000 - COMPUTERS / Hardware / Mainframes and Minicomputers, COM051360 - COMPUTERS / Programming Languages / Python
Publisher: Packt Publishing
Published: 2018-04-30T12:14:45+00:00


mkdir ~/bin mv shtdwn.py ~/bin/shtdwn.py crontab -e

At the end of the file, we add the following code:

@reboot sudo python3 ~/bin/shtdwn.py

How it works...

This time, when we set up the GPIO pin, we define the pin connected to the shutdown button as an input and the pin connected to the LED as an output. We turn the LED on to indicate that the system is running.

By setting the DEBUG flag to True, we can test the functionality of our script without causing an actual shutdown (by reading the terminal messages); we just need to ensure that we set DEBUG to False when using the script for real.

We enter a while loop and check the pin every second to see whether the GPIO pin is set to LOW (that is, to check whether the switch has been pressed); if so, we enter the doShutdown() function.

The program will wait for three seconds and then test again to see whether the button is still being pressed. If the button is no longer being pressed, we return to the previous while loop. However, if it is still being pressed after three seconds, the program will flash the LED and trigger the shutdown (and also provide an audio warning using flite).

When we are happy with how the script is operating, we can disable the DEBUG flag (by setting it to False) and add the script to crontab. crontab is a special program that runs in the background and allows us to schedule (at specific times, dates, or periodically) programs and actions when the system is started (@reboot). This allows the script to be started automatically every time the Raspberry Pi is powered up. When we press and hold the shutdown button for more than three seconds, it safely shuts down the system and enters a low power state (the LED switches off just before this, indicating that it is safe to remove the power shortly after). To restart the Raspberry Pi, we briefly remove the power; this will restart the system, and the LED will light up when the Raspberry Pi has loaded.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.